//
//  AddPhotoView.m
//  YunGou
//
//  Created by macbook on 16/5/19.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "AddPhotoView.h"
#import "NSObject+Tools.h"

@interface AddPhotoView ()
@end

@implementation AddPhotoView
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super initWithCoder:aDecoder]) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addPhoto:)];
        UIImage *addImage = [[UIImage imageNamed:@"xianji"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        [self.imageArray addObject:addImage];
        UIImageView *addImageView = [[UIImageView alloc] init];
        addImageView.userInteractionEnabled = YES;
        addImageView.image = addImage;
        [addImageView addGestureRecognizer:tap];
        [self addSubview:addImageView];
    }
    return self;
}

- (void)addImage:(UIImage *)image{
    [self.imageArray addObject:image];
    UIImageView *imageView = [[UIImageView alloc] init];
    imageView.image = image;
    imageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(addPhoto:)];
    [imageView addGestureRecognizer:tap];
    
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    deleteBtn.frame = CGRectMake(-8, -8, 16, 16);
    [deleteBtn setBackgroundImage:[UIImage imageNamed:@"xiugai"] forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
    [deleteBtn setAccessoryObject:imageView];
    [imageView addSubview:deleteBtn];
    [self addSubview:imageView];
}

- (void)layoutSubviews{
    CGFloat imageWH     = self.bounds.size.height - 8;
    CGFloat imageMargin = 20;
    CGFloat imageX      = 0;
    CGFloat imageY      = 8;
    NSInteger count = self.imageArray.count;
    for(NSInteger i = count - 1; i >= 0 ; i--){
        imageX = (imageMargin + imageWH) * i;
        UIImage *image = [self.imageArray objectAtIndex:count - 1 - i];
        UIImageView *iv = [self.subviews objectAtIndex:count - 1 - i];
        iv.image = image;
        iv.tag = count - 1 - i;
        [iv setFrame:CGRectMake(imageX, imageY, imageWH, imageWH)];
        
        UIImageView *firstImage = self.subviews[0];
        if (count == 4) {
            firstImage.hidden = YES;
        }else{
            firstImage.hidden = NO;
        }
    }
}

//点击图片事件
- (void)addPhoto:(UITapGestureRecognizer *)tap{
    if (self.imageTapBlock) {
        self.imageTapBlock((UIImageView *)tap.view);
    }
}

//点击删除图片
- (void)deleteImage:(UIButton *)btn{
    if (self.deleteImageBlock) {
        self.deleteImageBlock(btn);
    }
}

- (NSMutableArray *)imageArray{
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

- (void)dealloc{
    [self.imageArray removeAllObjects];
}

@end
